package touro.finances.control;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

import touro.finances.Main;
import touro.finances.gui.ExpensesPanel;
import touro.finances.model.Expense;
import touro.finances.model.FinancesDatabase;

public class AddExpenseController implements ActionListener{

	private ExpensesPanel ePanel;
	FinancesDatabase fd;

	public AddExpenseController(ExpensesPanel ePanel, FinancesDatabase fd){
		this.ePanel = ePanel;
		this.fd = fd;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		StringBuilder message = new StringBuilder();	//message to display if input errors
		boolean error = false;

		
			String amount = ePanel.getAmount();
			if(amount.isEmpty() || !amount.matches("\\d*\\.?\\d*")){
				message.append("Amount field contains invalid data.\n");
				error = true;
			}
			

		String date = ePanel.getDate();
		String[] dateArray = date.split("[/\\-]");
		int month=0, day=0, year=0;

		if(dateArray.length!=3){
			message.append("You are missing one or more of the date's fields");
			error = true;
		}
		else{

			month = Integer.parseInt(dateArray[0]);
			day = Integer.parseInt(dateArray[1]);
			year = Integer.parseInt(dateArray[2]);

			if(month<1 || month >12){
				message.append("The Month must be between 1(Jan) and 12(Dec).\n");
				error = true;
			}
			if(day<1){
				message.append("You cannot have less that one day in the month\n");
				error = true;
			}
			else if(dateArray[1].matches("[469(11)]") && day>30){	//regex is all months with 30 days
				message.append("The month cannot have more than 30 days.\n");
				error = true;
			}
			else if(month==2 && year%4!=0 && day>28){	//February, non-leap year(year%4)
				message.append("February cannot have more than 28 days in a non-leap year\n");
				error = true;
			}
			else if(month==2 && day>29){	//Feb, leap year
				message.append("February cannot have more than 28 days in a leap year.\n");
				error = true;
			}
			else if (day>31){
				message.append("The month cannot have more than 31 days.");
				error = true;
			}

		}

		if(error){
			JOptionPane.showMessageDialog(null, message, "Data Entry Error", JOptionPane.ERROR_MESSAGE);
		}
		else{
			Expense expense = new Expense(Double.parseDouble(amount),
					month, day, year, ePanel.getDescription());
			try{
				expense.insert(fd.getConnection(), fd);
				
				ePanel.setAmount("");
				ePanel.setDate("");
				ePanel.setLocationT("");
				ePanel.setDescription("");
			}
			catch(Exception ex){

			}
		}
	}

}
